const multer = require('multer');
const db = require('./db/db.js');

var storage = multer.diskStorage({
  destination: function(req, file, cb) {
    cb(null, 'www/uploads');
  },
  filename: function(req, file, cb) {
    // 在req加入一个属性file 等于一个file对象
    req.file = file;
    var name = req.cookies.name;
    var _id = req.cookies._id;
    // console.log(file);
    if (file.mimetype == "image/jpeg") {
      var extension = ".jpg";
    } else if (file.mimetype == "image/png") {
      var extension = ".png";
    } else if (file.mimetype == "image/gif") {
      var extension = ".gif";
    }
    var photo = { photo: "/uploads/" + name + extension }
    db.User.findByIdAndUpdate(_id, photo, function(err) {
      if (!err) {
        cb(null, name + extension);
      }
    });

  }
});
var upload = multer({ storage: storage });

module.exports = upload;
